var goodslist_cantegory_id = null; //定义分类搜索条件
var firstCategoryId = null;
var secondCategoryId = null;
var thirdCategoryId = null;
var fourthCategoryId = null;
var notJoinDataSource = [];// spu未加入商品分类加入数据列表
var joinDataSource = [];//spu加入商品的数据
var lastClassNotData = false;//三级分类是否有数据的标识
// 保存接口的spucodes
var spuCodeArr = [];//批量取消的加入的spuCodes集合
var newSpuCodeArr = [];
var tempSpuCodes = [];// 用于临时存储的spuCodes集合
var flag = false;// 是否选择已取消的商品的处理
var flagJoin = false;// 没有选择要加入的商品校验
var curCategoryObj = {};
/*二级场景id获取*/
if(getQueryString("id")){
    var id = getQueryString("id");
}
/*操作类型 新增、修改*/
if(getQueryString("operateType")){
    var operateType = getQueryString("operateType");
}
// 获取子级场景id
if(getQueryString("secondId")){
    var secondId = getQueryString("secondId");
}
var loginData = JSON.parse(web.readCookie("loginData"));
// 未加入商品的列表查询
var params = {
    pageSize:50,
    nowPage:1,
    model:{
        firstCategoryId:"",
        secondCategoryId:"",
        categoryId:"",
        saleStatus: "",
        spuCode:"",
        skuCode: "",
        helpCode:"",
        nameParam: "",
        brandParam:"",
        spuCodes:""
    }
}
// 已加入商品列表
var joinParams = {
    pageSize:50,
    nowPage:1,
    model:{
        firstCategoryId:null,
        secondCategoryId:null,
        categoryId:null,
        spuCode:"",
        aliasName:"",
        creationDateBegin:"",
        creationDateEnd:"",
        shelfDateBegin:"",
        shelfDateEnd:"",
        proSpuCode:"",
        helpcode:"",
        nameParam:"",
        brandParam:"",
        saleStatus:"",
        salesManParam:"",
        standards:"-1",
        restricted:"-1",
        customerType:"",
        specialTypeId:"",
        saleArea:"1,2",
        proUseable:"-1",
        spuCodes:""
    }
}
// 保存接口参数
var saveParams = {
    id:"",
    name:"",
    appSceneId:secondId,
    categoryId:"",
    categoryMuster:"",
    spuCode:"",
    coordinate:"",
    productType:""
}
// 获取接口数据
var getData = {
    //选择商品分类接口
    // 一级查询
    categoryByParamInfo:function(categoryLevel){
        //参数
        var params = {
            categoryLevel:categoryLevel,
            categoryName: ""
        }
        var successData = function(data){
            if(data.errorCode == 0){
                renderData.renderFirstDownLists(data.data)
            }
        }
       return  web.doAjax(root.goodsInter.categoryByParam, 'post', params, successData);
    },
    // 二级查询
    secondCategoryByParamInfo:function(category_id,level){
        var params = {
            parentCateId: category_id,
        }
        var successData = function(data){
            if(data.errorCode == 0){
                renderData.renderSecondDownLists(data.data,level)
            }
        }
       return  web.doAjax(root.goodsInter.categoryByParam, 'post', params, successData);
    },
    // 查询展示
    getNextInfo:function(level, category_id){
       if(level == 5) {
           goodslist_cantegory_id = category_id;
           fourthCategoryId = category_id;
       }
       if(level < 5){
           $("#class" + level + "")[0].oninput = function(){
               var params = {
                   parentCateId: category_id,
                   categoryName: $("#class" + level + "").val()
               }
               var successData = function(data){
                    if(data.errorCode == 0){
                        renderData.renderSecondDownLists(data.data,level)
                    }
               }
             return  web.doAjax(root.goodsInter.categoryByParam, 'post', params, successData);
           }
         /*  $("#class" + level + "").focus(function() {
               $("#classUl" + level + "").show();

           });*/
           $(document).bind("click", function(e) {
               if($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                   $("#classUl" + level + "").hide()
               }
           });
       }
   },
    /*spu页面*/
    // 选择类目
    initClassInfo:function(level,params){
        $.ajax({
            url: root.goodsInter.categoryByParam,
            cache: false, //禁用缓存
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            type: "POST",
            data: params,
            success:function(data){
                if(!!data){
                    if(data.data.length > 0){
                        var dataLists = data.data;
                        // 初始化一级类目
                        if(level == 0){
                            $.each(dataLists,function(index,item){
                                $("#rank1").append("<option value='" + item.category_id + "'>" + item.category_name + "</option>")
                            })
                        } else {
                            level = level + 1;
                            $.each(dataLists,function(index,item){
                                $("#rank" + level).append("<option value='" + item.category_id + "'>" + item.category_name + "</option>")
                            })
                        }
                    }
                }
            },
            error:function(msg){

            }
        });
    },
    // spu列表
    // 未加入列表
    spuListForStoreInfo:function(){
        $.ajax({
            contentType: 'application/json',
            url:root.sroreinter.spuListForStore,
            cache: false,  //禁用缓存
            type: "POST",
            data: JSON.stringify(params),
            beforeSend:function() {
                $(".load_img").show();
            },
            success: function (data) {
                $(".load_img").hide();
                if(data.errorCode == 0){
                    if(!!data.data && data.data.list.length >0){
                        var totalPage = data.data.totalPage;
                        renderData.renderNotJoinLists(data.data);
                        $(".M-box3").pagination({
                            pageCount: totalPage,
                            jump: true,
                            coping: true,
                            isHide: false,
                            prevContent: '上页',
                            nextContent: '下页',
                            callback:function(api){
                                params.nowPage = api.getCurrent();
                                // 全选恢复未选状态
                                $("#notJoinCheckAll").prop("checked",false)
                                $.ajax({
                                    contentType: 'application/json',
                                    url:root.sroreinter.spuListForStore,
                                    cache: false,  //禁用缓存
                                    type: "POST",
                                    data: JSON.stringify(params),
                                    beforeSend:function() {
                                        $(".load_img").show();
                                    },
                                    success:function(data){
                                        $(".load_img").hide();
                                        renderData.renderNotJoinLists(data.data);
                                    }
                                })
                            }
                        })

                    }else {
                        $(".M-box3").pagination({
                            pageCount:0
                        });
                        renderData.renderNotJoinLists(data.data);
                    }
                }
            },
            error:function(msg){
                $.Huimodalalert('请求失败',2000);
            }
        });
    },
    // 已加入
    spuListForStoreAddedInfo:function(){
        $.ajax({
            contentType: 'application/json',
            url:root.sroreinter.spuListForStoreAdded,
            cache: false,  //禁用缓存
            type: "POST",
            data: JSON.stringify(joinParams),
            beforeSend:function() {
                $(".load_img").show();
            },
            success: function (data) {
                $(".load_img").hide();
                if(data.errorCode == 0 ){
                    if(!!data.data && data.data.list.length >0){
                        var totalCount = data.data.totalPage;
                        renderData.renderJoinLists(data.data)
                        $(".M-box4").pagination({
                            pageCount: totalCount,
                            jump: true,
                            coping: true,
                            isHide: false,
                            prevContent: '上页',
                            nextContent: '下页',
                            callback:function(api){
                                joinParams.nowPage = api.getCurrent();
                                $.ajax({
                                    contentType: 'application/json',
                                    url:root.sroreinter.spuListForStoreAdded,
                                    cache: false,  //禁用缓存
                                    type: "POST",
                                    data: JSON.stringify(joinParams),
                                    beforeSend:function() {
                                        $(".load_img").show();
                                    },
                                    success:function(data){
                                        $(".load_img").hide();
                                        renderData.renderJoinLists(data.data)
                                    }
                                })
                            }
                        })
                    }else {
                        $(".M-box4").pagination({
                            pageCount:0
                        });
                        renderData.renderJoinLists(data.data)
                    }
                } else if(data.errorCode == 1010022){
                    $(".M-box4").pagination({
                        pageCount:0
                    });
                    // 全选按钮的处理
                    $("#joinCheckAll").prop("checked",false)
                    var emptyData = {
                        list:[]
                    };
                    renderData.renderJoinLists(emptyData)
                }

            },
            error:function(msg){
                $.Huimodalalert('请求失败',2000);
            }
        });
    },
    // 保存
    saveOrUpdateInfo:function(){
        var succCallBack = function(data, status, response) {
            if(data.errorCode == "0") {
                layer.msg("操作成功", {
                    icon: 6,
                    time: 1000
                }, function() {
                    colsePop();
                })
            }else if(data.errorCode == 1){
                $.Huimodalalert(data.msg,2000);
            }
        };
        return web.doAjax(root.sroreinter.appScenePoint_saveOrUpdate, 'post', saveParams, succCallBack,1);

    }
}
// 数据渲染
var renderData = {
    /*商品分类*/
    // 渲染第一级列表数据
    /*renderFirstDownLists:function(data){
        var itemLi = '';// 每条数据
        if(!data){
            itemLi = "<li>无数据</li>";
            $("#classUl1").html(itemLi)
        }else{
            for(var i = 0;i < data.length;i++){
                var item = data[i];
                itemLi += "<li onclick='nextClass(" + item.category_id + "," + item.category_level + ",\"" + item.category_name + "\")'>" + item.category_name + "</li>"
            }
            $("#classUl1").html(itemLi)
        }
    },
    // 渲染二三级列表数据
    renderSecondDownLists:function(data,level){
        var itemLi = '';
        var nextLevel = null;
        if(data.length <= 0){
            itemLi = "<li>无数据</li>";
            lastClassNotData = true;
        } else {
            lastClassNotData = false;
            for(var i =0; i<data.length;i++){
                var item = data[i];
                itemLi += "<li onclick='nextClass(" + item.category_id + "," + item.category_level + ",\"" + item.category_name + "\")'>" + item.category_name + "</li>"
            }
        }
        if(!data[0]){
            nextLevel = level + 1;
            $("#classUl" + nextLevel + "").html(itemLi);
            $("#classUl" + level + "").hide();
        } else {
            nextLevel = data[0].category_level;
            $("#classUl" + nextLevel + "").html(itemLi);
            $("#classUl" + nextLevel + "").show();
            $("#classUl" + level + "").hide()
        }
    },*/
    /*修改锚点-渲染锚点信息*/
    renderAnchorDataList:function(){
        $("#productType").val(dataResult.productType);
        $("#sceneName").val(dataResult.name);
        $("#sceneLocation").val(dataResult.coordinate);
        if(dataResult.categoryMuster){
            var categoryMuster = JSON.parse(dataResult.categoryMuster);
            curCategoryObj = {
                categoryId1: categoryMuster.categoryId1,
                categoryId2: categoryMuster.categoryId2,
                categoryId3: categoryMuster.categoryId3,
                categoryId4: categoryMuster.categoryId4,
                categoryName1: categoryMuster.categoryName1,
                categoryName2: categoryMuster.categoryName2,
                categoryName3: categoryMuster.categoryName3,
                categoryName4: categoryMuster.categoryName4,
            }
            if(!categoryMuster.categoryId4){
                curCategoryObj.category4NotData = true;
            }
            $("#class1").val(categoryMuster.categoryName1).attr("categoryid",categoryMuster.categoryId1);
            $("#class2").val(categoryMuster.categoryName2).attr("categoryid",categoryMuster.categoryId2);
            $("#class3").val(categoryMuster.categoryName3).attr("categoryid",categoryMuster.categoryId3);
            $("#class4").val(categoryMuster.categoryName4).attr("categoryid",categoryMuster.categoryId4);
        }
        // 根据分类展示列表信息 10 商品分类   20 spu
        if(dataResult.productType == 10){
            $("#categories").show();
        }else if(dataResult.productType == 20){
            $("#spu").show();
        }
    },
    /* spu商品*/
    // 渲染spu 类目
    /*changeClass:function(level){
        // 点击一级类目
        if(level == 1){
            $("#rank2").empty();
            $("#rank2").append("<option value=''>请选择二级品类名称</option>");
            $("#rank3").empty();
            $("#rank3").append("<option value=''>请选择三级品类名称</option>");
            $("#rank4").empty();
            $("#rank4").append("<option value=''>请选择四级品类名称</option>");
        }
        // 点击二级类目
        if(level == 2){
            $("#rank3").empty();
            $("#rank3").append("<option value=''>请选择三级品类名称</option>");
            $("#rank4").empty();
            $("#rank4").append("<option value=''>请选择四级品类名称</option>");
        }
        // 点击二级类目
        if(level == 3){
            $("#rank4").empty();
            $("#rank4").append("<option value=''>请选择四级品类名称</option>");
        }
        if($("rank"+level).val() != ""){
            getData.initClassInfo(level, {
                "parentCateId": $("#rank" + level + "").val()
            })
        }
    },*/
    // spu商品分类未加入列表
    renderNotJoinLists:function(data){
        notJoinDataSource = [];
        if(!!data && data.list.length > 0){
            $.each(data.list,function(index,item){
                var obj = {};
                obj.spu_code = item.spu_code;//SPU码
                obj.img_url = item.img_url;//图片
                obj.name = item.name;//商品名称
                obj.subtitile = item.subtitile;//副标题
                obj.brand_name = item.brand_name;//品牌
                obj.sku_number = item.sku_number;// SKU数量
                obj.skuPutOnNumber = item.skuPutOnNumber;//上架数量/SKU数量
                obj.salesmansName = item.salesmansName;//运营负责人
                obj.sale_area = item.sale_area;//商品区域
                obj.sale_status = item.sale_status;//状态
                obj.last_shelf_on_time = item.last_shelf_on_time;//最新上架时间
                obj.idAdded = item.idAdded;//是否已加入（0：未加入， 1： 已加入）
                notJoinDataSource.push(obj)
            })
        }
        renderData.notJoinLists(notJoinDataSource)
    },
    // spu商品分类未加入列表表格渲染
    notJoinLists:function(data){
        var datatable = $("#notJoinLists").dataTable(); // 初始化dataTable，清空上一个值
        datatable.fnClearTable();//清空一下table
        datatable.fnDestroy(); //还原初始化了的datatable
        $("#notJoinLists").DataTable({
            "order": [[ 1, "desc" ]],
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                }
            },
            data:data,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        if(row.idAdded==1){
                            var ischecked = 'checked="checked"';
                        }else {
                            var ischecked = '';
                        }
                        return '<span style="text-align: center;"><td><input class="notJoinCheck" type="checkbox" name="checkbox" '+ischecked+' onchange="selectOneFn(this)" data-spucode='+ row.spu_code +'></td></span>';
                    },
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var spu_code = row.spu_code;
                        if(spu_code == undefined){
                            spu_code = ''
                        }
                        return '<span style="text-align: center;" >'+spu_code+'</span>';

                    },
                    "targets": 1
                },
                {
                    "render": function(data, type, row, meta) {
                        var img_url = row.img_url;
                        if(!!img_url){
                            var val = '<span id="spuImg1" ><img onclick="picShow(\'查看图片\',\''+img_url+'\')" src="'+img_url+'" width="80" height="40"></span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }

                    },
                    "targets": 2
                },
                {
                    "render": function(data, type, row, meta) {
                        var name = row.name;
                        if(name == undefined){
                            name = ''
                        }
                        return  '<span style="text-align: center;">'+ name +'</span>';
                    },
                    "targets": 3
                },
                {
                    "render": function(data, type, row, meta) {
                        var subtitile = row.subtitile;
                        if(subtitile == undefined){
                            subtitile = ''
                        }
                        return  '<span style="text-align: center;">'+ subtitile +'</span>';
                    },
                    "targets": 4
                },
                {
                    "render": function(data, type, row, meta) {
                        var brand_name = row.brand_name;
                        if(brand_name == undefined){
                            brand_name = ''
                        }
                        return  '<span style="text-align: center;">'+ brand_name +'</span>';
                    },
                    "targets": 5
                },
                {
                    "render": function(data, type, row, meta) {
                        var sku_number = row.sku_number;
                        if(sku_number == undefined){
                            sku_number = ''
                        }
                        return  '<span style="text-align: center;">'+ sku_number  +'</span>';
                    },
                    "targets": 6
                },
                {
                    "render": function(data, type, row, meta) {
                        // 判断展示已加入还是未加入 是否已加入（0：未加入， 1： 已加入）
                        if(row.idAdded == 0){
                            return ' <input type="button" onclick="joinOne(\''+row.spu_code+'\')" class="btn btn-secondary size-S radius ml-20"  id="btn-'+row.spu_code+'" value="加&nbsp;&nbsp;入">';
                        }else if(row.idAdded == 1){
                            return  '<span class="btn-'+row.spu_code+'" style="text-align: center;">'+"已加入"+'</span>'
                        }
                    },
                    "targets": 7
                },
            ],
            fnInitComplete:function(){
                $("#notJoinLists").on("change",".notJoinCheck",function(){
                    var num = $(".notJoinTables").find("input[type=checkbox]:checked").length;
                    var selectTotalLength = $(".notJoinCheck").length;
                    if(num == selectTotalLength){
                        $("#notJoinCheckAll").prop("checked",true)
                    }else {
                        $("#notJoinCheckAll").prop("checked",false)
                    }
                });
               // alert($("#notJoinCheckAll").is(":checked") + '未加入')
                if($("#notJoinCheckAll").is(":checked")){
                    // 全部选中状态
                    $.each($(".notJoinCheck"),function(index,item){
                        $(item).prop('checked',true)
                    });
                }
            }
        })
    },
    // spu商品分类加入列表
    renderJoinLists:function(data){
        joinDataSource = [];
        if(data.list.length > 0){
            spuCodeArr = [];
            $.each(data.list,function(index,item){
                var obj = {};
                obj.spu_code = item.spu_code;//SPU码
                obj.img_url = item.img_url;//图片
                obj.name = item.name;//商品名称
                obj.subtitile = item.subtitile;//副标题
                obj.brand_name = item.brand_name;//品牌
                obj.sku_number = item.sku_number;//上架数量/SKU数量
                obj.salesmansName = item.salesmansName;//运营负责人
                obj.sale_area = item.sale_area;//商品区域
                obj.sale_status = item.sale_status;//状态
                obj.last_shelf_on_time = item.last_shelf_on_time;//最新上架时间
                obj.idAdded = item.idAdded;//是否已保存
                if(item.idAdded==1){
                    spuCodeArr.push(item.spu_code);
                }
                joinDataSource.push(obj)
            })
        }else{
            renderData.joinLists([])
        }
        renderData.joinLists(joinDataSource)
    },
    // spu商品分类加入如类别数据表格渲染
    joinLists:function(data){
        var datatable = $("#joinLists").dataTable(); // 初始化dataTable，清空上一个值
        datatable.fnClearTable();//清空一下table
        datatable.fnDestroy(); //还原初始化了的datatable
        $("#joinLists").DataTable({
            "order": [[ 1, "desc" ]],
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                }
            },
            data:data,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        return '<span style="text-align: center;"><td><input class="joinCheck" type="checkbox" onchange="selectOneForSaveFn(this)" name="checkbox" data-spucode='+ row.spu_code +'></td></span>';
                    },
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var spu_code = row.spu_code;
                        if(spu_code == undefined){
                            spu_code = ''
                        }
                        return '<span style="text-align: center;" >'+spu_code+'</span>';

                    },
                    "targets": 1
                },
                {
                    "render": function(data, type, row, meta) {
                        var img_url = row.img_url;
                        if(!!img_url){
                            var val = '<span id="spuImg1" ><img onclick="picShow(\'查看图片\',\''+img_url+'\')" src="'+img_url+'" width="80" height="40"></span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 2
                },
                {
                    "render": function(data, type, row, meta) {
                        var name = row.name;
                        if(name == undefined){
                            name = ''
                        }
                        return  '<span style="text-align: center;">'+ name +'</span>';
                    },
                    "targets": 3
                },
                {
                    "render": function(data, type, row, meta) {
                        var subtitile = row.subtitile;
                        if(subtitile == undefined){
                            subtitile = ''
                        }
                        return  '<span style="text-align: center;">'+ subtitile +'</span>';
                    },
                    "targets": 4
                },
                {
                    "render": function(data, type, row, meta) {
                        var brand_name = row.brand_name;
                        if(brand_name == undefined){
                            brand_name = ''
                        }
                        return  '<span style="text-align: center;">'+ brand_name +'</span>';
                    },
                    "targets": 5
                },
                {
                    "render": function(data, type, row, meta) {
                        var sku_number = row.sku_number;
                        if(sku_number == undefined){
                            sku_number = ''
                        }
                        return  '<span style="text-align: center;">'+ sku_number +'</span>';
                    },
                    "targets": 6
                },

                {
                    "render": function(data, type, row, meta) {
                        return ' <span style="text-align: center;">'+ '已加入' +'</span>' ;
                    },
                    "targets": 7
                },
            ],
            fnInitComplete:function(){
                $("#joinLists").on("change",".joinCheck",function(){
                    var num = $(".joinTables").find("input[type=checkbox]:checked").length;
                    var selectTotalLength = $(".joinCheck").length;
                    if(num == selectTotalLength){
                        $("#joinCheckAll").prop("checked",true)
                    }else {
                        $("#joinCheckAll").prop("checked",false)
                    }
                })
               // alert($("#joinCheckAll").is(":checked") + '已加入')
                if($("#joinCheckAll").is(":checked")){
                    $.each($(".joinCheck"),function(index,item){
                        $(item).prop("checked",true)
                    })
                }
            }
        })
    }
}
if(operateType=="edit"){ //productType
    var dataResult = parent.sceneAnchorData;
    renderData.renderAnchorDataList();
    tempSpuCodes.push(dataResult.spuCode)
    joinParams.model.spuCodes = dataResult.spuCode;
    getData.spuListForStoreAddedInfo();
}
//下拉框监听事件
$("#productType").change(function(){
   var value = $("#productType option:selected").val();
   if(value == "10"){ // 商品分类
       $("#categories").show();
       $("#spu").hide();
   }
   if(value == "20"){ // spu
       $("#categories").hide();
       $("#spu").show();
   }
})
// 选择锚点
function selectScene(){
    layer.open({
        type:2,
        title: "图片",
        content:['sceneAnchorPop.html?secondId=' + secondId, 'no'],
        area:['1010px','550px'],
        scrollbar: false,
        shadeClose: true,
        move: false,

    })
    //layer_show('图片', 'sceneAnchorPop.html?secondId=' + secondId , "1010", "550");
}
// 获取弹窗图片坐标位置
function callback(station){
    $("#sceneLocation").val(station)
}

// 逻辑处理
/*/!* 商品分类模块 start*!/
function productTypeEvent(){
    $("#class1").click(function(){
        $("#classUl1").show();
        getData.categoryByParamInfo(1);
    })
}
function nextClass(category_id,level,category_name){
    $("#class" + level + "").val(category_name).attr("categoryid",category_id);
    if(level == 1) {
        params.model.firstCategoryId = category_id;
        $("#class2").val("").attr("categoryid","");
        $("#class3").val("").attr("categoryid","");
        $("#class4").val("").attr("categoryid","");
    } else if(level == 2) {
        params.model.secondCategoryId = category_id;
        $("#class3").val("").attr("categoryid","");
        $("#class4").val("").attr("categoryid","");
    } else if(level == 3) {
        params.model.thirdCategoryId = category_id;
        $("#class4").val("").attr("categoryid","");
    }
    getData.secondCategoryByParamInfo(category_id,level)
    getData.getNextInfo(level + 1, category_id)
}
$("#class1").focus(function() {
    $("#classUl2").hide();
    $("#classUl3").hide();
    $("#classUl1").show();
})
$("#class2").focus(function() {
    $("#classUl2").show();
    $("#classUl3").hide();
    $("#classUl1").hide();
    var categoryid = $("#class1").attr("categoryid");
    getData.secondCategoryByParamInfo(categoryid)

})
$("#class3").focus(function() {
    $("#classUl2").hide();
    $("#classUl1").hide();
    $("#classUl3").show();
    var categoryid = $("#class2").attr("categoryid");
    getData.secondCategoryByParamInfo(categoryid)
})
/!* 商品分类模块 end*!/*/


/*spu商品 start*/
// 初始选择类目
/*getData.initClassInfo(0, {
    "categoryLevel": 1
})
// 其他类目选择
$("#rank1").change(function () {
    renderData.changeClass(1);
});
$("#rank2").change(function () {
   renderData.changeClass(2);
});
$("#rank3").change(function () {
    renderData.changeClass(3);
});
$("#rank4").change(function () {
    renderData.changeClass(4);
});*/
// 查看大图
function picShow(title, imgUrl) {
    var url = '../../goods/picShow.html'
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
    sessionStorage.setItem("imgUrl", imgUrl);
    layer_show(title, url, "800", "500");
}
// 未加入列表切换展示
function noJoin(){
    $(".tabBar").children("span").eq(0).addClass("current")
    $(".tabBar").children("span").eq(1).removeClass("current")
    $("#no_join_list").show();
    $("#join_list").hide();
    params.model.spuCodes = spuCodeArr.join(",");
    params.nowPage = 1;
    getData.spuListForStoreInfo();

}
// 加入切换
function join(){
    $(".tabBar").children("span").eq(0).removeClass("current")
    $(".tabBar").children("span").eq(1).addClass("current")
    $("#join_list").show();
    $("#no_join_list").hide();
    joinParams.model.spuCodes =spuCodeArr.join(",");
    joinParams.nowPage = 1;
    getData.spuListForStoreAddedInfo();
}
// 查询按钮
function search(){
    console.log(_categoryData);
    // 筛选的第一类条目id
    var firstCategoryId = _categoryData.categoryId1;
    // 二级条目id
    var secondCategoryId = _categoryData.categoryId2;
    // 三级条目id
    var thirdCategoryId = _categoryData.categoryId3;
    // 四级条目id
    var categoryId = _categoryData.categoryId4;
    // 上下架状态
    var saleStatus = $("#state option:selected").val();
    // SPU码
    var spuCode = $("#spuCode").val();
   //Code码
    var skuCode = $("#skuCode").val();
    // 商品助记码
    var helpCode = $("#helpCode").val();
    // 商品名称
    var nameParam = $("#spuName").val();
    //品牌关键字
    var brandParam = $("#brand").val();
    params.model.firstCategoryId = firstCategoryId;
    params.model.secondCategoryId = secondCategoryId;
    params.model.thirdCategoryId = thirdCategoryId;
    params.model.categoryId = categoryId;
    params.model.saleStatus = saleStatus;
    params.model.spuCode = spuCode;
    params.model.skuCode = skuCode;
    params.model.helpCode = helpCode;
    params.model.nameParam = nameParam;
    params.model.brandParam = brandParam;
    if(operateType=="edit"){
       params.model.spuCodes = dataResult.spuCode;
    }
   getData.spuListForStoreInfo();
}
// 重置
function resetTables(){
    // 表格选择数据清空
    $('#rank1').find("option:contains('请选择一级品类名称')").prop("selected", true);//一级品类
    $('#rank2').html("<option value=''>请选择二级品类名称</option>");//二级品类
    $('#rank3').html("<option value=''>请选择三级品类名称</option>");//三级品类
    $('#state').find("option:contains('状态')").prop("selected",true);//状态
    $('#spuCode').val('');//SPU码
    $('#skuCode').val('');//Code码
    $('#helpCode').val('');//商品助记码
    $('#spuName').val('');//商品名称
    $('#brand').val('');//品牌关键字
}
/*未保存数据列表复选框操作函数*/
function selectOneFn(el) {
    var notJoinSpu = ''
    if($(el).prop("checked")){
         notJoinSpu = $(el).attr("data-spucode");
        tempSpuCodes.push(notJoinSpu)
    } else {
        deleteOneInArr(notJoinSpu,tempSpuCodes);
    }
}
/*已选商品列表复选框操作函数*/
function selectOneForSaveFn(el) {
    var joinSpu = '';
    if($(el).prop("checked")){
        // 获取选择加入商品的spu编码
         joinSpu = $(el).attr("data-spucode");
        // 放入要取消加入的商品中
        newSpuCodeArr.push(joinSpu);

    }else{
        deleteOneInArr(joinSpu,newSpuCodeArr);
    }
}
//批量添加
function batchJoin() {
    noSelectJoin();
    if(!flagJoin){
        if( Array.from(new Set(tempSpuCodes)).length <=50){
            spuCodeArr = Array.from(new Set(tempSpuCodes))
        }else{
            $.Huimodalalert('最多添加50个商品',2000);
        }
            joinParams.model.spuCodes =spuCodeArr.join(",");
            getData.spuListForStoreAddedInfo();
    }
    // 对全选商品编号去重处理
    /*数组去重方案一*/
/*    var temp = [];
    for(var i =0;i<tempSpuCodes.length;i++){
        var item = tempSpuCodes[i];
        if(temp.indexOf(item) == -1){
            temp.push(item)
        }
    }*/
}
// 没有选择加入校验
function noSelectJoin(){
    $.each($(".notJoinCheck"),function(index,item){
        if($(item).is(":checked")) {
            var spuCode = item.getAttribute('data-spucode');
            Array.from(new Set(tempSpuCodes)).push(spuCode)
        }
    })
    if( Array.from(new Set(tempSpuCodes)).length <=0){
        flagJoin = true;
        $.Huimodalalert('请选择要加入的商品',2000);
    } else {
        flagJoin = false
    }
}
//加入一条
function joinOne(spuCode) {
    if(spuCodeArr.length >= 50){
        $.Huimodalalert('最多添加50个商品',2000);
        return
    }
    spuCodeArr.push(spuCode);
    $("#btn-" + spuCode + "").parent().html("<span  class='btn-"+spuCode+"'  style=\"text-align: center;\">"+'已加入'+"</span>");
}
//批量取消
function cancelChecked(){
    noSelectCancel();
    if(!flag){
        var ary1 = Array.from(new Set(spuCodeArr));
        var ary2 = Array.from(new Set(newSpuCodeArr));
        var difference = ary1.filter(function(item){
            return !ary2.includes(item)
        });
        // spuCodeArr 重新赋值
        spuCodeArr = difference;
        joinParams.model.spuCodes =spuCodeArr.join(",");
        getData.spuListForStoreAddedInfo();
    }
}
// 批量取消未选的取消处理
function noSelectCancel(){
    // 未勾选部分提示选择要取消的商品
    $.each( $(".joinCheck"),function(index,item){
        if($(item).is(":checked")){
            var spuCode = item.getAttribute('data-spucode');
            Array.from(new Set(newSpuCodeArr)).push(spuCode)
        }
    })
    if(Array.from(new Set(newSpuCodeArr)).length <= 0){
        flag = true;
        $.Huimodalalert('请选择要取消的商品',2000);
    }else{
        flag = false;
    }
}
/*//全部取消
function cancelAll(){
    // spuCodeArr=[];
    if(spuCodeArr.length <=0){
        $.Huimodalalert('请选择要取消的数据',2000);
        return
    }
    save();
}*/
// 全部选择未加入商品
function selectAll(){
    if($("#notJoinCheckAll").is(":checked")){
        // 全部选中状态
        $.each($(".notJoinCheck"),function(index,item){
            $(item).prop('checked',true)
            var spus = $(item).attr('data-spucode')
            // 放入临时的spuCodes集合
            tempSpuCodes.push(spus);
        });
    }else{
        $.each( $(".notJoinCheck"),function(index,item){
            $(item).prop('checked',false)
        })
    }
}
// 全部选择已加入的商品
function selectAllJoin(){
    if($("#joinCheckAll").is(":checked")){
        // 全部选中状态
        $.each($(".joinCheck"),function(index,item){
            $(item).prop("checked",true)
            var spus = $(item).attr('data-spucode');
            newSpuCodeArr.push(spus)
        })
    }else{
        $.each($(".joinCheck"),function(index,item){
            $(item).prop("checked",false)
        })
        newSpuCodeArr = [];
    }
}
// 保存按钮
function saveBtn(){
    console.log(_categoryData)
    if(JSON.stringify(_categoryData) != "{}"){
        curCategoryObj = _categoryData;
    }
    var value = $("#productType option:selected").val();
    //条件判断
    if(!$("#productType option:selected").val()){
        $.Huimodalalert('请选择锚点类型',2000);
        return;
    } else if(!$("#sceneName").val()){
        $.Huimodalalert('请填写锚点名称',2000);
        return;

    }else if(!$("#sceneLocation").val()){
        $.Huimodalalert('请选择锚点位置',2000);
        return;
    }
    if(value == "10"){ //商品分类
        // 必选判断
        if(!curCategoryObj.categoryId1){
            $.Huimodalalert('请选择一级分类',2000);
            return;
        }
        if(!curCategoryObj.categoryId2){
            $.Huimodalalert('请选择二级分类',2000);
            return;
        }
        if(!curCategoryObj.categoryId3){
            $.Huimodalalert('请选择三级分类',2000);
            return;
        }
        if(!curCategoryObj.category4NotData && !curCategoryObj.categoryId4){
            $.Huimodalalert('请选择四级分类',2000);
            return;
        }
        saveParams.productType = value;
        saveParams.name = $("#sceneName").val();
        saveParams.coordinate = $("#sceneLocation").val();
        // 分类选择类别
        let categoryMuster = {
            categoryId1: curCategoryObj.categoryId1,
            categoryId2: curCategoryObj.categoryId2,
            categoryId3: curCategoryObj.categoryId3,
            categoryId4: curCategoryObj.categoryId4,
            categoryName1: curCategoryObj.categoryName1,
            categoryName2: curCategoryObj.categoryName2,
            categoryName3: curCategoryObj.categoryName3,
            categoryName4: curCategoryObj.categoryName4,
        };
        saveParams.categoryMuster = JSON.stringify(categoryMuster);
        saveParams.categoryId = curCategoryObj.categoryId4;
        if(curCategoryObj.category4NotData && !curCategoryObj.categoryId4){
            saveParams.categoryId = curCategoryObj.categoryId3;
        }
        if(lastClassNotData.category3NotData && !_categoryData.categoryId3){
            saveParams.categoryId = _categoryData.categoryId2;
        }
    }else  if(value == "20"){//spu
        // spu场景下的保存操作
        var spuCodeStr = spuCodeArr.join(",");
        saveParams.name = $("#sceneName").val();
        saveParams.spuCode =spuCodeStr;
        saveParams.coordinate = $("#sceneLocation").val();
        saveParams.productType = value;
    }
    if(operateType=="add"){
        saveParams.creatorId = loginData.user.user_ID;
        saveParams.creatorName = loginData.user.username;
        saveParams.id = "";
    }else if(operateType=="edit"){
        saveParams.modifyId =loginData.user.user_ID;
        saveParams.modifyName = loginData.user.username;
        saveParams.id = id;
    }
    getData.saveOrUpdateInfo();

}
// 取消
function cancel(){
    parent.layer.closeAll();
}
/*删除数组某个指定元素*/
function deleteOneInArr(str,arr) {
    var index = arr.indexOf(str);
    arr.splice(index,1);
}
/*关闭弹框并刷新列表*/
function colsePop() {
    parent.getData.sceneAnchorListsInfo();
    parent.layer.closeAll();
    getData.spuListForStoreAddedInfo();
}

